//
//  SearchByLineResultViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-6-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "SearchByLineResultViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "TrainStation.h"
#import "LineListCellViewController.h"


@implementation SearchByLineResultViewController

@synthesize resultTable, result;

NSString *line;

- (void)search
{
    /**
     12.2 火车票车次查询接口
     请求地址: /trainline.php
     请求参数:   
     action    = 'get_trainline_by_train';
     train_code  车次
     date = 日期 例子:03-15
     
     返回参数: 
     train_code 车次
     station 停靠站
     start_time 发时
     end_time 到时
     times 历时
     返回格式事例: 
     <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>get_trainline_by_train</transcode></head><body><trainline><trainstation><train_code>T272</train_code><station>吉林西</station><start_time>21:36</start_time><end_time>----</end_time><times>--</times></trainstation><trainstation><train_code>T272</train_code><station>九台</station><start_time>22:42</start_time><end_time>22:38</end_time><times>01:02</times></trainstation><trainstation><train_code>T272</train_code><station>长春</station><start_time>23:55</start_time><end_time>23:20</end_time><times>01:44</times></trainstation><trainstation><train_code>T272</train_code><station>铁岭</station><start_time>01:55</start_time><end_time>01:53</end_time><times>04:17</times></trainstation><trainstation><train_code>T272</train_code><station>沈阳北</station><start_time>02:42</start_time><end_time>02:34</end_time><times>04:58</times></trainstation><trainstation><train_code>T272</train_code><station>锦州南</station><start_time>04:57</start_time><end_time>04:44</end_time><times>07:08</times></trainstation><trainstation><train_code>T272</train_code><station>山海关</station><start_time>06:47</start_time><end_time>06:37</end_time><times>09:01</times></trainstation><trainstation><train_code>T272</train_code><station>北京</station><start_time>----</start_time><end_time>09:40</end_time><times>12:04</times></trainstation></trainline></body></msg>
     */
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"trainline.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:4];
    [param setObject:@"get_trainline_by_train" forKey:@"action"];
    [param setObject:line forKey:@"train_code"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd"];
    NSString *stringFromDate = [formatter stringFromDate: [NSDate date]];
    [param setObject:stringFromDate forKey:@"date"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
}

- (void)iRequestFinished:(NSData *)response
{
    
    [app hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
//    NSLog(@"--------rootElement:--------\n%@", rootElement);
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
//    NSLog(@"--------bodyElement:--------\n%@", bodyElement);
    
    //某个具体节点的文本内容
    //某个具体节点的文本内容
    GDataXMLElement* trainElement = [[bodyElement elementsForName:@"trainline"]objectAtIndex:0];
    
    NSArray *items = [trainElement elementsForName:@"trainstation"];    
    result =  [[NSMutableArray alloc] initWithCapacity:[items count]];
    
    for (int i = 0; i < [items count]; i ++){
        GDataXMLElement *element = [items objectAtIndex:i];
        
        
        NSArray *arr = [element children];
        
        NSString *trainCode;
        NSString *station;
        NSString *startTime;
        NSString *endTime;
        NSString *times;
        
        for (int j = 0; j<[arr count]; j++) {
            GDataXMLNode *node = [arr objectAtIndex:j];
            
            NSString* key = [node name];
            NSLog(@"--------GDataXMLNode:--------\n%@:%@", key, [node stringValue]);
            if ([key isEqualToString:@"train_code"]){
                trainCode = [node stringValue];
            } else if  ([key isEqualToString:@"station"]){
                station = [node stringValue];
            } else if  ([key isEqualToString:@"start_time"]){
                startTime = [node stringValue];                               
            } else if  ([key isEqualToString:@"end_time"]){
                endTime = [node stringValue];                 
            } else if  ([key isEqualToString:@"times"]){
                times = [node stringValue];
            }
        }
        
        TrainStation *trainStation = [[[TrainStation alloc] init] autorelease];
        trainStation.trainCode = trainCode;
        trainStation.station = station;
        trainStation.startTime = startTime;
        trainStation.endTime = endTime;
        trainStation.times = times;
        
        [result addObject:trainStation];
    }


    NSLog(@"--------TrainStation:--------\n%@", result);
    
    [doc release];
    
    [resultTable reloadData];
}

- (void) setQueryParam:(NSString *)l
{
    line = l;
    NSLog(@"line-----%@\n", line);
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [resultTable setDelegate:self];
    [resultTable setDataSource:self];
    
    app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    [self search];
    [self.navigationItem setTitle:@"车次查询"];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [result count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCellIdentifier = @"SearchByLineCell";
    
    LineListCellViewController *cell = (LineListCellViewController *)[tableView dequeueReusableCellWithIdentifier:kCellIdentifier]; 
    if (cell == nil) { 
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LineListCellView" owner:self options:nil]; 
        cell = [array objectAtIndex:0]; 
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
    } 
    
    TrainStation *station = [result objectAtIndex:indexPath.row];
    
    NSInteger num = indexPath.row + 1;
    cell.number.text = [NSString stringWithFormat:@"%i", num];
    cell.trainCode.text = station.station;
    cell.startTime.text = station.startTime;
    cell.endTime.text = station.endTime;
    cell.time.text = station.times;
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  

{       
    return 90; 
}
@end
